package cn.bupt.adt.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.dao.autogenerate.CheckInstiAppUserMapper;
import cn.bupt.adt.dao.autogenerate.CheckInstiMapper;
import cn.bupt.adt.entity.autogenerate.CheckInsti;
import cn.bupt.adt.entity.autogenerate.CheckInstiAppUser;
import cn.bupt.adt.entity.autogenerate.CheckInstiAppUserExample;
import cn.bupt.adt.entity.autogenerate.CheckInstiExample;
import cn.bupt.adt.entity.autogenerate.Institution;
import cn.bupt.adt.model.CheckInstitutionModel;
import cn.bupt.adt.service.ICheckInstitutionService;
import cn.bupt.adt.util.AccountUtil;
import cn.bupt.adt.util.BeanUtil;
import cn.bupt.adt.util.ImageUtil;
import cn.bupt.adt.util.MD5Util;
import cn.bupt.adt.util.SendSMSUtil;
@Service
public class CheckInstitutionService implements ICheckInstitutionService {

	@Autowired
	CheckInstiMapper checkInstiMapper;
	
	@Autowired
	CheckInstiAppUserMapper checkInstiAppUserMapper;
	@Override
	public List<CheckInsti> getAllInstitutions() {
		return checkInstiMapper.selectByExample(new CheckInstiExample());
	}

	private List<CheckInstitutionModel> transferModel(List<CheckInsti> checks) {
		List<CheckInstitutionModel> res = new ArrayList<CheckInstitutionModel>(checks.size());
		CheckInstitutionModel cm = null;
		for(CheckInsti c:checks) {
			cm = new CheckInstitutionModel();
			try {
				BeanUtil.fatherToChild(c, cm);
			} catch (Exception e) {
				e.printStackTrace();
			}
			cm.setAppears(ImageUtil.convertToList(c.getAppearenceImg()));
		}
		return res;
	}
	private CheckInstitutionModel transferModel(CheckInsti check) {
		CheckInstitutionModel cm = new CheckInstitutionModel();
			try {
				BeanUtil.fatherToChild(check, cm);
			} catch (Exception e) {
				e.printStackTrace();
			}
			cm.setAppears(ImageUtil.convertToList(check.getAppearenceImg()));
		return cm;
	}

	@Override
	public synchronized boolean addInstitution(CheckInsti ins, HttpServletRequest request) {
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
		String rootPath = req.getSession().getServletContext().getRealPath("")+"/../"+Constants.IMAGE_PATH;
		List<MultipartFile> appears = req.getFiles("appears");
		MultipartFile certs = req.getFile("certs");
		Long time = System.currentTimeMillis();
		String timePath = time.toString()+"/";
		List<String> path = new ArrayList<>();
		try {
			ObjectMapper mapper = new ObjectMapper();
			int i = 0;
			for(MultipartFile appearFile:appears) {
				path.add(ImageUtil.uploadImage(appearFile, Constants.CHECKINS_APPEAR+timePath, rootPath,i));
				i++;
			}
			
			ins.setAppearenceImg(mapper.writeValueAsString(path));
			path.clear();
			ins.setCertificationImg(ImageUtil.uploadImage(certs, Constants.CHECKINS_CERT, rootPath, 1));
		}
		catch(Exception e){
			
		}
		//新增的机构的联系电话不能与已有机构的电话相同
		CheckInstiExample ex = new CheckInstiExample();
		ex.createCriteria().andPhoneEqualTo(ins.getPhone());
		List<CheckInsti> institutions = checkInstiMapper.selectByExample(ex);
		if(institutions.size() != 0)
			return false;
		//向机构表插入
		int i = checkInstiMapper.insert(ins);
		
		//为机构生成账号与密码，账号不能与已有机构的账号相同
		CheckInstiAppUser appUser = new CheckInstiAppUser();
		List<CheckInstiAppUser> appUsers = checkInstiAppUserMapper.selectByExample(new CheckInstiAppUserExample());
		Set<String> accounts = new HashSet<>();
		for(CheckInstiAppUser u:appUsers)
			accounts.add(u.getAccount());
		appUser.setAccount(generateAccount(accounts,Constants.ACCOUNT_LENGTH));
		String passwd = generatePasswd(Constants.PASSWD_LENGTH);
		appUser.setPasswd(MD5Util.MD5(passwd));
		appUser.setCheckInstiId(ins.getId());
		//向客户端机构表插入
		int j = checkInstiAppUserMapper.insert(appUser);
		//给检查机构发送短信，告知账号密码
		SendSMSUtil sendSms = new SendSMSUtil();
		sendSms.SendSMS(ins.getPhone(), new String[]{appUser.getAccount(),passwd}, Constants.SMS_CHECKINS_INVATECODE);
		return i == 1 && j == 1;
	}
	private String generateAccount(Set<String> accounts,int len) {
		String res = null;
		do {
			res = AccountUtil.getRandomAccount(len);
		}while(accounts.contains(res));
		return res;
	}
	private String generatePasswd(int len) {
		return AccountUtil.getRandomAccount(len);
	}
	@Override
	public boolean deleteInstitutionById(int id) {
		return checkInstiMapper.deleteByPrimaryKey(id) == 1;
	}

	@Override
	public boolean modifyInstitution(CheckInsti ins, HttpServletRequest request) {
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
		String rootPath = req.getSession().getServletContext().getRealPath("")+"/../"+Constants.IMAGE_PATH;
		List<MultipartFile> appears = req.getFiles("appear");
		MultipartFile certs = req.getFile("certi");
		Long time = System.currentTimeMillis();
		String timePath = time.toString()+"/";
		List<String> path = new ArrayList<>();
		try {
			ObjectMapper mapper = new ObjectMapper();
			int i = 0;
			if(appears.size() != 0 && appears.get(0).getSize() != 0) {
				for(MultipartFile appearFile:appears) {
					path.add(ImageUtil.uploadImage(appearFile, Constants.APPEAR_PATH+timePath, rootPath,i));
					i++;
				}
				ins.setAppearenceImg(mapper.writeValueAsString(path));
				path.clear();
			}
			if(certs != null && certs.getSize() != 0) {
				ins.setCertificationImg(ImageUtil.uploadImage(certs, Constants.CHECKINS_CERT+timePath, rootPath, 1));
			}
		}
		catch(Exception e){
			
		}		
		return checkInstiMapper.updateByPrimaryKeySelective(ins) == 1;
	}

	@Override
	public CheckInstitutionModel getInstitutionById(int id) {
		CheckInsti check = checkInstiMapper.selectByPrimaryKey(id);
		return transferModel(check);
	}

}
